/*
** multedit.c
**
** Pictor, Version 1.51, Copyright (c) 1992-94 SoftCircuits
** Redistributed by permission.
*/

#include <string.h> /* <string.h> holds strlen in wcc- W. Jones */
#include "pictor.h"


#define MAX_LINES 10
extern int _PL_tabendedit;
extern int _PL_editfill;

/*
** Displays a window with mutiple edit fields. kbdedit is used for
** editing each field. The user can tab between the different fields.
** Returns TRUE if the user presses Enter, FALSE if Escape.
*/
int multiedit(MEDITSTRUCT *items,int numitems,char *title,
	COLORSTRUCT *colors)
{
	int i,j,maxprompt = 0,maxlen = 0,done = FALSE;
	int top,left,height,width,editcol,curritem,retval = 0;

	if(numitems == 0) return(FALSE);
	if(numitems > MAX_LINES) numitems = MAX_LINES;

	for(i = 0;i < numitems;i++) {
		if((int)strlen(items[i].prompt) > maxprompt)
			maxprompt = strlen(items[i].prompt);
		if(items[i].maxlen > maxlen)
			maxlen = items[i].maxlen;
	}
	maxlen++;
	width = maxprompt + maxlen + 6;
	i = width - (_PL_columns - 10);
	if(i > 0) {
		maxlen -= i;
		width -= i;
	}
	height = (numitems * 2) + 1;

	top = center(height + 2,_PL_rows);
	left = center(width + 2,_PL_columns);

	editcol = left + maxprompt + 5;

	if(!wopen(top,left,height + 2,width + 2,colors->normal,WO_SHADOW)) {
		messagebox("Insufficient memory",title,MB_OK,colors);
		return(FALSE);
	}
	wtitle(title);

	for(i = 0;i < numitems;i++) {

		/* prompt */
		setwpos(2 + (i * 2),(maxprompt + 2) - strlen(items[i].prompt));
		wputs(items[i].prompt);

		/* vcolor(colors->normal); */
		setvpos(top + 2 + (i * 2),editcol - 3);
		vputs(": [");

		for(j = 0;j < maxlen;j++) {
			if(j < (int)strlen(items[i].buffer))
				vputc(items[i].buffer[j]);
			else
				vputc((char)_PL_editfill);
		}
		vcolor(colors->normal);
		vputc(']');
	}

	_PL_tabendedit = TRUE;
	curritem = 0;

	while(!done) {
		switch(kbdedit(items[curritem].buffer,top + 2 + (curritem * 2),
			editcol,maxlen,items[curritem].maxlen,colors)) {

			case -1:    /* tab */
				if(++curritem >= numitems)
					curritem = 0;
				break;
			case -2:    /* shift-tab */
				if(--curritem < 0)
					curritem = (numitems - 1);
				break;
			case 0:     /* escape */
				retval = FALSE;
				done = TRUE;
				break;
			default:    /* return */
				retval = TRUE;
				done = TRUE;
				break;
		}
	}
	_PL_tabendedit = FALSE;
	wclose();

	return(retval);

} /* multiedit */
